package com.monkeygroup.mygoplus.common.utils;

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.monkeygroup.mygoplus.thing.vo.ZoneVO;



/**
 * 功能说明:工具类
 * 作    者:
 * 创建日期:2015/11/4 13:03
 * 所属项目:通用1.0
 */
public class Tools {
    public static final String PERMISSION_STATUS = "permission_status";
    public static final String CAMERA_PERMISSION_STATUS = "camera_permission_status";
    public static final String STORAGE_PERMISSION_STATUS = "storage_permission_status";

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static int px2sp(Activity context, float pxValue, float k) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (k * pxValue / fontScale + 0.5f);
    }


    public static SharedPreferences getSharePreferences(Context context,
                                                        String name) {
        SharedPreferences sh = context.getSharedPreferences(name,
                Context.MODE_PRIVATE);
        return sh;
    }

    public static boolean checkConnection(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.isConnected()) {
            return true;
        }
        return false;
    }

    public static void closeInputWindow(Activity activity) {
        try {
            InputMethodManager inputMethodManager = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(activity
                            .getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {

        }
    }

    public static int getScreenWidth(Activity activity) {
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels; // 屏幕宽度（像素）
        return width;
    }

    public static int getScreenHeight(Activity activity) {
        DisplayMetrics metric = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int height = metric.heightPixels; // 屏幕宽度（像素）
        return height;
    }


    public static String safeString(EditText et) {
        String source = et.getText().toString();
        if (source.length() == 0) {
            return "";
        } else {
            String re = source.trim().replace("}", "").replace("{", "")
                    .replace("<", "").replace(">", "").replace("]", "")
                    .replace("[", "").replace("\"", "");
            return re;
        }
    }

	/**
	 * 将double转为数值，并最多保留num位小数。例如当num为2时，1.268为1.27，1.2仍为1.2；1仍为1，而非1.00;100.00则返回100。
	 *
	 * @param d
	 * @param num 小数位数
	 * @return
	 */
	public static String double2String(double d, int num) {
		NumberFormat nf = NumberFormat.getNumberInstance();
		nf.setMaximumFractionDigits(num);//保留两位小数
		nf.setGroupingUsed(false);//去掉数值中的千位分隔符

		String temp = nf.format(d);
		if (temp.contains(".")) {
			String s1 = temp.split("\\.")[0];
			String s2 = temp.split("\\.")[1];
			for (int i = s2.length(); i > 0; --i) {
				if (!s2.substring(i - 1, i).equals("0")) {
					return s1 + "." + s2.substring(0, i);
				}
			}
			return s1;
		}
		return temp;
	}

	/**
	 * 将double转为数值，并最多保留num位小数。
	 *
	 * @param d
	 * @param num 小数个数
	 * @param defValue 默认值。当d为null时，返回该值。
	 * @return
	 */
	public static String double2String(Double d, int num, String defValue){
		if(d==null){
			return defValue;
		}

		return double2String(d,num);
	}
	
	//textview部分文字颜色
	public static void spannableString(String spannableString,String content,TextView txtProjectDetail,int color){
		
		SpannableStringBuilder builder = new SpannableStringBuilder(spannableString+content);  
		//ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色  
		ForegroundColorSpan redSpan = new ForegroundColorSpan(color);  
		builder.setSpan(redSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//		txtProjectDetail.setText(Html.fromHtml("<span style='color:#58cbc3'>[解决方案说明] </span> 说明说明说明"));
        txtProjectDetail.setText(builder);

    }

    /**
     * 验证手机号
     *
     * @param str
     * @return
     */
    public static boolean isMobile(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }


	/**
	 * 读取城市地区
	 * @param inputStream
	 * @return
	 */
	public static List<ZoneVO> getString(String pid, InputStream inputStream, String searchKey,String id) {
		InputStreamReader inputStreamReader = null;
		try {
			inputStreamReader = new InputStreamReader(inputStream, "gbk");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		BufferedReader reader = new BufferedReader(inputStreamReader);

		List<ZoneVO> zoneList = new ArrayList<ZoneVO>();
		String line;
		try {
			while ((line = reader.readLine()) != null) {

				String[] zone = line.split(",");

				if(pid.equals(zone[2])){

					ZoneVO vo = new ZoneVO();
					if(!StringUtil.isBlank(id)){
						//查詢某一個城市
						if(id.equals(zone[0])){
							vo.setId(zone[0]);
							vo.setName(zone[1]);
							vo.setPid(zone[2]);
							if(zone.length>3){
								vo.setLat(zone[3]);
								vo.setLng(zone[4]);
							}
							if(!StringUtil.isBlank(searchKey)){
								if(vo.getName().contains(searchKey)){
									zoneList.add(vo);
								}
							}
							else{
								zoneList.add(vo);
							}
						}

					}
					else{
						vo.setId(zone[0]);
						vo.setName(zone[1]);
						vo.setPid(zone[2]);
						if(zone.length>3){
							vo.setLat(zone[3]);
							vo.setLng(zone[4]);
						}
						if(!StringUtil.isBlank(searchKey)){
							if(vo.getName().contains(searchKey)){
								zoneList.add(vo);
							}
						}
						else{
							zoneList.add(vo);
						}
					}

				}


			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return zoneList;
	}
 
}
